package com.shop.zzh.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.gridfs.GridFSDBFile;
import com.shop.zzh.config.FtpAttConfig;
import com.shop.zzh.entity.ZcVideo;
import com.shop.zzh.result.ResultForm;
import com.shop.zzh.service.VideoService;
import com.shop.zzh.utils.FtpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: shop
 * @description: 文件上传控制类
 * @author: zhuzh
 * @create: 2019-11-28 09:34
 **/

@Api(value = "文件上传下载控制类")
@RestController
@RequestMapping("/file")
public class MongoDBGFSController {

	private static final Logger logger = LoggerFactory.getLogger(MongoDBGFSController.class);

	@Autowired
	private GridFsTemplate gridFsTemplate;

	@Autowired
	private GridFSBucket gridFSBucket;

	@Autowired
	private FtpAttConfig ftpAttConfig;

	@Autowired
	private VideoService videoServide;

	/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	@ApiOperation(value = "上传文件测试", notes = "上传文件测试")
	@RequestMapping(value="/upload")
	public ResultForm uploadFile(@RequestParam("videoName")String videoName,@RequestParam("videoType")String videoType,@RequestParam("videoDuration")String videoDuration,
								 @RequestParam("videoJj")String videoJj,@RequestParam("videoStatus")String videoStatus,@RequestParam("file") MultipartFile[] file) throws Exception {
		FTPClient ftpClient = null;
		ZcVideo video = null;
		for (int i = 0; i < file.length; i++) {
			//连接ftp服务器
			ftpClient =  FtpUtils.getFTPClient(ftpAttConfig.getFtpHost(), ftpAttConfig.getFtpPort(), ftpAttConfig.getFtpUserName(), ftpAttConfig.getFtpPassWord());
			// 获得提交的文件名
			String fileName = file[i].getOriginalFilename();
			// 获取文件输入流
			InputStream ins = file[i].getInputStream();
			// 获取文件类型
			String contentType = file[i].getContentType();
			//上传文件到ftp
			boolean flag = FtpUtils.uploadFile(ftpClient,"",ftpAttConfig.getTruePath()+ "\\" +contentType+ "\\" + UUID.randomUUID(),fileName,file[i].getInputStream());
			if(flag){
				// 将文件存储到mongodb中
				ObjectId objectId = gridFsTemplate.store(ins, fileName, contentType);
				logger.info("保存成功，objectId:" + objectId);
				//新增视频
				if(video!=null){
					if(video.getImgId()!=""&&video.getImgId()!=null){
						video.setVideoId(objectId.toString());
						video.setVideoPath("/video/show?file_id="+objectId.toString());
					}else{
						video.setImgId(objectId.toString());
						video.setImgPath("/video/show?file_id="+objectId.toString());
					}
				}else{
					video = new ZcVideo();
					video.setId(UUID.randomUUID().toString());
					video.setVideoName(videoName);
					video.setVideoType(videoType);
					video.setVideoDuration(videoDuration);
					video.setVideoJj(videoJj);
					video.setVideoStatus(videoStatus);
					if(contentType.contains("images")){//图片
						video.setImgId(objectId.toString());
						video.setImgPath("/video/show?file_id="+objectId.toString());
					}else{//视频
						video.setVideoId(objectId.toString());
						video.setVideoPath("/video/show?file_id="+objectId.toString());
					}
					video.setVideoWatchTimes(0);
					video.setVideoDownloadTimes(0);
					video.setVideoCreateDate(new Date());
					video.setVideoCreateUserId("zzh");
				}
			}else{
				return  new ResultForm(flag,"上传失败");
			}

		}
		videoServide.insertVideo(video);
		//关闭ftp连接
		FtpUtils.disconnectFTPClient(ftpClient);
		return new ResultForm(true,"上传成功");
	}


	/**
	 * 下载文件
	 *
	 * @param fileId
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ApiOperation(value = "下载文件测试", notes = "下载文件测试demo")
	@RequestMapping(value = "/download", method = {RequestMethod.GET, RequestMethod.POST})
	public void downloadFile(@RequestParam(name = "file_id") String fileId,
							 HttpServletRequest request,
							 HttpServletResponse response) throws IOException {
		logger.info("准备下载文件....");
		Query query = Query.query(Criteria.where("_id").is(fileId));
		// 查询单个文件
		GridFSFile gridFSFile = gridFsTemplate.findOne(query);
		if (gridFSFile == null) {
			return;
		}

		String fileName = gridFSFile.getFilename().replace(",", "");
		String contentType = gridFSFile.getMetadata().get("_contentType").toString();



		// 通知浏览器进行文件下载
		response.setContentType(contentType);
		response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
		GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
		GridFsResource resource = new GridFsResource(gridFSFile, gridFSDownloadStream);

		OutputStream outputStream = response.getOutputStream();
		InputStream inputStream = resource.getInputStream();
		IOUtils.copy(inputStream, outputStream);
		outputStream.flush();
		outputStream.close();
		inputStream.close();
	}


	/**
	 * 预览图片
	 *
	 * @param fileId
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@ApiOperation(value = "页面显示", notes = "页面显示")
	@RequestMapping(value = "/show", method = RequestMethod.GET)
	public void showFile(@RequestParam(name = "file_id") String fileId,
							 HttpServletRequest request,
							 HttpServletResponse response) throws IOException {
		logger.info("准备下载文件....");
		Query query = Query.query(Criteria.where("_id").is(fileId));
		// 查询单个文件
		GridFSFile gridFSFile = gridFsTemplate.findOne(query);
		if (gridFSFile != null) {
			// mongo-java-driver3.x以上的版本就变成了这种方式获取
			GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
			GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
			String fileName = gridFSFile.getFilename().replace(",", "");
			//处理中文文件名乱码
			if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
					request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
					|| request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
				fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			} else {
				//非IE浏览器的处理：
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}
			response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");
			IOUtils.copy(gridFsResource.getInputStream(), response.getOutputStream());
		}
	}
}
